using System;
using System.Collections.Generic;

namespace TrueCode.Core
{
  public class ServiceProvider : IServiceProvider 
  {
    private readonly Dictionary< Type, object > _services = new Dictionary< Type, object >();

    #region Implementation of IServiceProvider
    public void AddService< T >( object service )
    {
      AddService( typeof( T ), service );
    }

    public void AddService( Type serviceType, object service )
    {
      if( ! serviceType.IsAssignableFrom( service.GetType() ) )
      {
        var exc = new ArgumentException( "Instance of the service cannot be cast to serviceType", "service" );
        exc.Data.Add( "serviceType", serviceType );
        exc.Data.Add( "service", service );
        throw exc;
      }

      _services.Add( serviceType, service );
    }

    public T GetService< T >()
    {
      return (T)GetService( typeof(T) );
    }
    #endregion

    #region Implementation of IServiceProvider
    public object GetService( Type serviceType )
    {
      object service;
      _services.TryGetValue( serviceType, out service );
      return  service;
    }
    #endregion
  }
}